// cloudfunctions/queryOrder/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { orderId } = event
    
    if (!orderId) {
      return {
        success: false,
        message: '订单ID缺失'
      }
    }
    
    // 查询订单信息
    const order = await db.collection('orders').doc(orderId).get()
    
    if (!order.data) {
      return {
        success: false,
        message: '订单不存在'
      }
    }
    
    // 格式化订单数据
    const orderData = order.data
    orderData.payTime = formatDate(orderData.payTime)
    
    return {
      success: true,
      orderData: orderData
    }
    
  } catch (error) {
    console.error('查询订单失败:', error)
    return {
      success: false,
      message: error.message || '查询订单失败'
    }
  }
}

// 格式化日期
function formatDate(date) {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`
}